var CAPABILITIES = null,
WMSURL = null, 
CAPABILITIES_URL = null,
LAST_LAYER_NAME_FILTER = null;
    
$(document).ready(function(){
    $('#addLayer').attr('disable',true);
    // estetica de los botones
    $('#layerGetter').button();
    $('#addLayer').button();
    // eventos en botones
    $('#layerGetter').click(function(){ 
        getWMSCapabilities($('#urlInput').val(),$('#layerNameFilter').val().trim());
    });
    $('#addLayer').click(function(){
        var selRow = $('#layers').jqGrid('getGridParam', 'selrow');
        if(selRow) {
            var selectedLayer = $('#layers').jqGrid ('getCell', selRow, 'layerName');
           
                     
            var srsArray = $('#srss_'+selectedLayer +' option').map(function(){
                return this.value;
            }).get();
            
            goToManageLayer(selectedLayer,srsArray); 
        }
        else {
            alert('Debe seleccionar una capa.');
        }
    });
    //Inicializo la tabla de layers
    $('#layers').jqGrid(
    {
        datatype : 'local',
        data: [],
        height: '230px',
        width:'auto',
        rowNum: 10,
        colNames: ['Capa', 'SRS', 'Formatos', 'Bounding Box'  ],
        colModel:[
            {
                name:'layerName', 
                align:"center",
                width:160
            },
            {
                name:'srs', 
                width:100, 
                align:"center",
                sortable: false
            },
            {
                name:'format', 
                width:100,
                align:"center",
                sortable: false
                    
            },
               
            {
                name:'bbox', 
                width:250, 
                align:"center",
                sortable: false
            }
            
        
           
        ],
        caption: "Capas Disponibles en el servidor WMS",
        cellEdit: true,
        cellsubmit: 'clientArray',
        gridview: true,
        pager: '#pager'
                
                
    });
    $(document).delegate('.gridSrsSelector','change',function(){
        var rowId = $(this).parent().parent().attr('id');
        updateSRSBbox(rowId ,$(this).val());
    });
    $('#gridWrap').hide();
    
})
function updateLayersGrid (layerNameFilter) {
    LAST_LAYER_NAME_FILTER = layerNameFilter; // Recuerdo el último filtro para no volver a filtrar si no cambia
    //limpio la grilla
    $('#layers').clearGridData(true);
    $('#noResults').hide();
    var gridData = [];
    var gridIndex = 0; // indice para insertar una row en la grilla
    $.each (CAPABILITIES.capability.layers , function(index,layer){
        if (!layerNameFilter || layer.name.toLowerCase().indexOf(layerNameFilter) != -1) {
            // creo el dropdown de los SRS
            var srsSelect = $('<select></select>').addClass('gridSrsSelector');
            srsSelect.attr('id','srss_'+layer.name);
            $.each(layer.srs, function(k, v) {   
                if(v) {
                    srsSelect
                    .append($("<option></option>")
                    .attr("value",k)
                    .text(k)); 
                }
            });
            // creo el dropdown de formatos
            var formatSelect = $('<select></select>');
            formatSelect.attr('id','formats_'+layer.name);
            $.each(layer.formats, function(i, value) {   
                
                formatSelect
                .append($("<option></option>")
                .attr("value",value)
                .text(value)); 
            });
            var bbox = layer.bbox[srsSelect.val()] != undefined ? layer.bbox[srsSelect.val()].bbox : layer.llbbox;
            var layerObject = {
                layerName : layer.name,
                format: formatSelect[0].outerHTML,
                     
                srs : srsSelect[0].outerHTML,
                bbox: bbox.toString()
                    
                };
            gridData[gridIndex++] = layerObject;
        }  
               
    } );
    if (gridData.length > 0) {
        $('#layers').jqGrid('setGridParam',{
            data:gridData
        }).trigger('reloadGrid');
        $('#gridWrap').show();
        $('#addLayer').attr('disable',false);
    }
    else {
        $('#gridWrap').hide();
        $('#noResults').show();
        $('#addLayer').attr('disable',true);
    }

}
/**
 * Llamada ajax al servicio WMS para obtener el documento capabilities 
 * y llenar la tabla con los resultados.
 *
 **/
function getWMSCapabilities (url,layerNameFilter) {
    if (url != CAPABILITIES_URL || !CAPABILITIES) {   
        var format = new OpenLayers.Format.WMSCapabilities();
    
        OpenLayers.ProxyHost = "/cgi-bin/proxy.php?url=";    
        OpenLayers.Request.GET({
            url: encodeURI(url+'?service=wms&request=GetCapabilities'),
        
            success: function(request) {
                var doc = request.responseXML;
                if (!doc || !doc.documentElement) {
                    doc = request.responseText;
                }
                // seteo las variables globales
                CAPABILITIES_URL = url+'&request=GetCapabilities';
                
                CAPABILITIES = format.read(doc);
                
                if(CAPABILITIES.error) {
                    showErrorDialog();
                    return;
                }
                
                WMSURL = url;
                updateLayersGrid(layerNameFilter);
                         
            },
            failure: function() {
                showErrorDialog();
                OpenLayers.Console.error.apply(OpenLayers.Console, arguments);
            }
        });
    
    }
    else if (layerNameFilter != LAST_LAYER_NAME_FILTER){
        updateLayersGrid(layerNameFilter);
    }
}
function goToManageLayer(layer, srsArray ) {
    $('<form action="manageLayer/initmanageLayer" method="POST">' + 
        '<input type="hidden" name="layer" value="' + layer + '"/>' +
        '<input type="hidden" name="srss" value="' + srsArray + '"/>' +
        '<input type="hidden" name="WMSURL" value="' + WMSURL + '"/>' +
        '</form>').appendTo(document.body).submit();
   
}
function updateSRSBbox(rowId, srs) {
    var rowData = $('#layers').jqGrid('getRowData', rowId);
    var layerName = rowData.layerName;
    var grid = $('#layers');
    var layer =  $.grep(CAPABILITIES.capability.layers, function(e){ return e.name == layerName; })[0];                      
    var newBbox =  layer.bbox[srs] != undefined ? layer.bbox[srs].bbox.toString() : layer.llbbox.toString();
//    var newUnits = mapUnits[defaultSRSData.units];
   
    grid.jqGrid('setCell', rowId, 'bbox', newBbox);
    grid.jqGrid('getLocalRow', rowId).bbox = newBbox;  
    
//    grid.jqGrid('setCell', rowId, 'units', newUnits);
//    grid.jqGrid('getLocalRow', rowId).units = newUnits;    
    
   
    
}
function showErrorDialog() {
    alert("No se pudo obtener el documento Capabilities");
}
